﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.Menu;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;
using System.Transactions;

namespace B.S.BasicData.Api.Write.Application.Handler.Menu
{
    public class AddRoleMenuHandler : IRequestHandler<AddRoleMenuCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<RoleModel> roleRepo;
        private readonly IBaseRepository<MenuModel> menuRepo;
        private readonly IBaseRepository<RoleMenuModel> roleMenuRepo;
      

        public AddRoleMenuHandler(IBaseRepository<RoleModel> roleRepo,IBaseRepository<MenuModel> menuRepo,IBaseRepository<RoleMenuModel> roleMenuRepo)
        {
            this.roleRepo = roleRepo;
            this.menuRepo = menuRepo;
            this.roleMenuRepo = roleMenuRepo;
            
        }
        /// <summary>
        /// 角色分配权限
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<int>> Handle(AddRoleMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            using (TransactionScope tran=new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                var rolemenu = roleMenuRepo.GetAll().Where(x => x.Rid == request.RoleId).ToList();
                roleMenuRepo.Delete(rolemenu);
                List<RoleMenuModel> roleMenuModels = new List<RoleMenuModel>();
                foreach (var item in request.MenuId)
                {
                    roleMenuModels.Add(new RoleMenuModel()
                    {
                        Mid=item,
                        Rid=request.RoleId,
                    });
                }
                int count = roleMenuRepo.AddAsnyc(roleMenuModels);
                if (count>0)
                {
                    res.Code = ApiEnum.Success;
                    res.Msg = "分配成功";
                }
                else
                {
                    res.Code = ApiEnum.Error;
                    res.Msg = "分配失败";
                }
                tran.Complete();
                return Task.FromResult(res);
            }
        }
    }
}
